package com.dmall.content.service.impl;

import com.dmall.content.mapper.ContentMapper;
import com.dmall.content.pojo.TbContent;
import com.dmall.content.service.ContentService;
import com.dmall.jedis.JedisClient;
import com.dmall.framework.result.DmallResult;
import com.dmall.utils.JsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

/**
 * @author Chen 2017/10/22
 */
@Service
public class ContentServiceImpl implements ContentService {
    @Autowired
    private ContentMapper contentMapper;
    @Autowired
    private JedisClient jedisClient;

    @Value("${CONTENT_LIST}")
    private String CONTENT_LIST;


    @Override
    public DmallResult addContent(TbContent content) {
        content.setCreated(new Date());
        content.setCreated(new Date());
        contentMapper.insert(content);
        //缓存同步，删除缓存中的对应的数据
        jedisClient.hdel(CONTENT_LIST,content.getCategoryId().toString());
        return DmallResult.ok();
    }

    /**
     * 根据类型Id查询内容列表
     */
    @Override
    public List<TbContent> getContentListByCid(Long cid) {
        //查询缓存
            try {
                String json = jedisClient.hget(CONTENT_LIST, cid + "");
                if(StringUtils.isNotBlank(json)){
                    List<TbContent> list  = JsonUtils.jsonToList(json,TbContent.class);
                    return list;
                }
            }catch (Exception e){

                //TODO 日志
                e.printStackTrace();
            }
        Example example = new Example(TbContent.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("categoryId",cid);
        List<TbContent> list = contentMapper.selectByExample(example);
        //添加结果到缓存
        try {
            jedisClient.hset(CONTENT_LIST,cid+"",JsonUtils.objectToJson(list));
        }catch (Exception e){
            e.printStackTrace();
        }
        return list;
    }
}
